// 路由创建/编辑组件
const RoutesCreate = {
    template: `
        <div class="form-container">
            <div class="form-header">
                <h2 class="form-title">{{ isEdit ? '编辑路由' : '创建路由' }}</h2>
            </div>
            
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="基本信息" name="basic">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="form.name" placeholder="路由名称，例如：api-route"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="URI" prop="uri">
                            <el-input v-model="form.uri" placeholder="请求路径，例如：/api/v1"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="主机名" prop="host">
                            <el-input v-model="form.host" placeholder="可选，例如：example.com"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="请求方法">
                            <el-checkbox-group v-model="form.methods">
                                <el-checkbox label="GET">GET</el-checkbox>
                                <el-checkbox label="POST">POST</el-checkbox>
                                <el-checkbox label="PUT">PUT</el-checkbox>
                                <el-checkbox label="DELETE">DELETE</el-checkbox>
                                <el-checkbox label="PATCH">PATCH</el-checkbox>
                                <el-checkbox label="HEAD">HEAD</el-checkbox>
                                <el-checkbox label="OPTIONS">OPTIONS</el-checkbox>
                            </el-checkbox-group>
                            <div class="form-item-tip">不选择表示匹配所有方法</div>
                        </el-form-item>
                        
                        <el-form-item label="状态">
                            <el-switch
                                v-model="form.status"
                                active-text="启用"
                                inactive-text="禁用">
                            </el-switch>
                        </el-form-item>
                        
                        <el-form-item label="描述" prop="description">
                            <el-input type="textarea" v-model="form.description" rows="3"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    
                    <el-tab-pane label="上游配置" name="upstream">
                        <el-form-item label="上游类型">
                            <el-radio-group v-model="upstreamType">
                                <el-radio label="inline">内联上游</el-radio>
                                <el-radio label="reference">引用已有上游</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        
                        <template v-if="upstreamType === 'reference'">
                            <el-form-item label="选择上游" prop="upstreamId">
                                <el-select v-model="form.upstreamId" filterable placeholder="请选择上游">
                                    <el-option
                                        v-for="item in upstreams"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                        
                        <template v-else>
                            <el-form-item label="负载均衡算法">
                                <el-select v-model="form.upstream.type" placeholder="请选择负载均衡算法">
                                    <el-option label="轮询" value="roundrobin"></el-option>
                                    <el-option label="一致性哈希" value="chash"></el-option>
                                    <el-option label="最少连接" value="least_conn"></el-option>
                                </el-select>
                            </el-form-item>
                            
                            <el-form-item label="上游节点">
                                <div v-for="(node, index) in upstreamNodes" :key="index" class="upstream-node">
                                    <el-input v-model="node.host" placeholder="主机" style="width: 40%; margin-right: 10px;"></el-input>
                                    <el-input-number v-model="node.port" :min="1" :max="65535" placeholder="端口" style="width: 20%; margin-right: 10px;"></el-input-number>
                                    <el-input-number v-model="node.weight" :min="0" :max="100" placeholder="权重" style="width: 20%; margin-right: 10px;"></el-input-number>
                                    <el-button type="danger" icon="el-icon-delete" circle @click="removeNode(index)"></el-button>
                                </div>
                                <el-button type="primary" icon="el-icon-plus" @click="addNode">添加节点</el-button>
                            </el-form-item>
                        </template>
                    </el-tab-pane>
                    
                    <el-tab-pane label="插件配置" name="plugins">
                        <el-form-item label="JWT认证">
                            <el-switch v-model="plugins.jwtAuth.enabled"></el-switch>
                        </el-form-item>
                        
                        <template v-if="plugins.jwtAuth.enabled">
                            <el-form-item label="JWT头部名称">
                                <el-input v-model="plugins.jwtAuth.config.header" placeholder="默认：Authorization"></el-input>
                            </el-form-item>
                            
                            <el-form-item label="查询参数名称">
                                <el-input v-model="plugins.jwtAuth.config.query" placeholder="默认：token"></el-input>
                            </el-form-item>
                        </template>
                        
                        <el-divider></el-divider>
                        
                        <el-form-item label="限流">
                            <el-switch v-model="plugins.limitCount.enabled"></el-switch>
                        </el-form-item>
                        
                        <template v-if="plugins.limitCount.enabled">
                            <el-form-item label="请求数量">
                                <el-input-number v-model="plugins.limitCount.config.count" :min="1"></el-input-number>
                            </el-form-item>
                            
                            <el-form-item label="时间窗口(秒)">
                                <el-input-number v-model="plugins.limitCount.config.time_window" :min="1"></el-input-number>
                            </el-form-item>
                            
                            <el-form-item label="拒绝状态码">
                                <el-input-number v-model="plugins.limitCount.config.rejected_code" :min="200" :max="599"></el-input-number>
                            </el-form-item>
                        </template>
                        
                        <el-divider></el-divider>
                        
                        <el-form-item label="CORS">
                            <el-switch v-model="plugins.cors.enabled"></el-switch>
                        </el-form-item>
                        
                        <template v-if="plugins.cors.enabled">
                            <el-form-item label="允许的来源">
                                <el-input v-model="plugins.cors.config.allow_origins" placeholder="*"></el-input>
                                <div class="form-item-tip">多个来源使用逗号分隔，或使用*表示允许所有来源</div>
                            </el-form-item>
                            
                            <el-form-item label="允许的方法">
                                <el-checkbox-group v-model="plugins.cors.config.allow_methods">
                                    <el-checkbox label="GET">GET</el-checkbox>
                                    <el-checkbox label="POST">POST</el-checkbox>
                                    <el-checkbox label="PUT">PUT</el-checkbox>
                                    <el-checkbox label="DELETE">DELETE</el-checkbox>
                                    <el-checkbox label="PATCH">PATCH</el-checkbox>
                                    <el-checkbox label="HEAD">HEAD</el-checkbox>
                                    <el-checkbox label="OPTIONS">OPTIONS</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </template>
                    </el-tab-pane>
                </el-tabs>
                
                <div class="form-footer">
                    <el-button @click="goBack">取消</el-button>
                    <el-button type="primary" @click="submitForm">{{ isEdit ? '保存' : '创建' }}</el-button>
                </div>
            </el-form>
        </div>
    `,
    props: {
        id: {
            type: [String, Number],
            required: false
        }
    },
    data() {
        return {
            activeTab: 'basic',
            loading: false,
            upstreamType: 'inline',
            form: {
                name: '',
                uri: '',
                host: '',
                methods: [],
                status: true,
                description: '',
                upstreamId: '',
                upstream: {
                    type: 'roundrobin',
                    nodes: {}
                }
            },
            upstreamNodes: [
                { host: '', port: 80, weight: 1 }
            ],
            upstreams: [
                { id: 1, name: '示例上游1' },
                { id: 2, name: '示例上游2' }
            ],
            plugins: {
                jwtAuth: {
                    enabled: false,
                    config: {
                        header: 'Authorization',
                        query: 'token'
                    }
                },
                limitCount: {
                    enabled: false,
                    config: {
                        count: 100,
                        time_window: 60,
                        rejected_code: 429
                    }
                },
                cors: {
                    enabled: false,
                    config: {
                        allow_origins: '*',
                        allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']
                    }
                }
            },
            rules: {
                name: [
                    { required: true, message: '请输入路由名称', trigger: 'blur' },
                    { pattern: /^[a-z0-9-_]+$/, message: '路由名称只能包含小写字母、数字、连字符和下划线', trigger: 'blur' }
                ],
                uri: [
                    { required: true, message: '请输入URI', trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        isEdit() {
            return !!this.id;
        }
    },
    created() {
        if (this.isEdit) {
            this.fetchRoute();
        }
    },
    methods: {
        fetchRoute() {
            this.loading = true;
            
            // 模拟获取路由数据
            setTimeout(() => {
                const route = {
                    id: this.id,
                    name: "example-route",
                    uri: "/example",
                    methods: ["GET", "POST"],
                    status: true,
                    description: "示例路由",
                    plugins: {
                        "jwt-auth": {
                            "header": "Authorization",
                            "query": "token"
                        },
                        "limit-count": {
                            "count": 100,
                            "time_window": 60,
                            "rejected_code": 429
                        }
                    },
                    upstream: {
                        type: "roundrobin",
                        nodes: {
                            "example.com:80": 1,
                            "backup.example.com:80": 1
                        }
                    }
                };
                
                // 填充表单数据
                this.form.name = route.name;
                this.form.uri = route.uri;
                this.form.host = route.host || '';
                this.form.methods = route.methods || [];
                this.form.status = route.status;
                this.form.description = route.description;
                
                // 处理上游数据
                if (route.upstream) {
                    if (route.upstream.id) {
                        this.upstreamType = 'reference';
                        this.form.upstreamId = route.upstream.id;
                    } else {
                        this.upstreamType = 'inline';
                        this.form.upstream.type = route.upstream.type;
                        
                        // 处理节点数据
                        this.upstreamNodes = [];
                        if (route.upstream.nodes) {
                            Object.entries(route.upstream.nodes).forEach(([target, weight]) => {
                                const [host, port] = target.split(':');
                                this.upstreamNodes.push({
                                    host,
                                    port: parseInt(port),
                                    weight
                                });
                            });
                        }
                    }
                }
                
                // 处理插件数据
                if (route.plugins) {
                    // JWT认证插件
                    if (route.plugins['jwt-auth']) {
                        this.plugins.jwtAuth.enabled = true;
                        this.plugins.jwtAuth.config = {
                            header: route.plugins['jwt-auth'].header || 'Authorization',
                            query: route.plugins['jwt-auth'].query || 'token'
                        };
                    }
                    
                    // 限流插件
                    if (route.plugins['limit-count']) {
                        this.plugins.limitCount.enabled = true;
                        this.plugins.limitCount.config = {
                            count: route.plugins['limit-count'].count || 100,
                            time_window: route.plugins['limit-count'].time_window || 60,
                            rejected_code: route.plugins['limit-count'].rejected_code || 429
                        };
                    }
                    
                    // CORS插件
                    if (route.plugins['cors']) {
                        this.plugins.cors.enabled = true;
                        this.plugins.cors.config = {
                            allow_origins: route.plugins['cors'].allow_origins || '*',
                            allow_methods: route.plugins['cors'].allow_methods || ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']
                        };
                    }
                }
                
                this.loading = false;
            }, 500);
        },
        addNode() {
            this.upstreamNodes.push({ host: '', port: 80, weight: 1 });
        },
        removeNode(index) {
            this.upstreamNodes.splice(index, 1);
        },
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    // 构建提交数据
                    const formData = {
                        name: this.form.name,
                        uri: this.form.uri,
                        host: this.form.host || undefined,
                        methods: this.form.methods.length > 0 ? this.form.methods : undefined,
                        status: this.form.status,
                        description: this.form.description
                    };
                    
                    // 处理上游数据
                    if (this.upstreamType === 'reference') {
                        formData.upstream = {
                            id: this.form.upstreamId
                        };
                    } else {
                        const nodes = {};
                        let hasValidNode = false;
                        
                        this.upstreamNodes.forEach(node => {
                            if (node.host && node.port) {
                                nodes[`${node.host}:${node.port}`] = node.weight;
                                hasValidNode = true;
                            }
                        });
                        
                        if (hasValidNode) {
                            formData.upstream = {
                                type: this.form.upstream.type,
                                nodes: nodes
                            };
                        }
                    }
                    
                    // 处理插件数据
                    const plugins = {};
                    
                    // JWT认证插件
                    if (this.plugins.jwtAuth.enabled) {
                        plugins['jwt-auth'] = this.plugins.jwtAuth.config;
                    }
                    
                    // 限流插件
                    if (this.plugins.limitCount.enabled) {
                        plugins['limit-count'] = this.plugins.limitCount.config;
                    }
                    
                    // CORS插件
                    if (this.plugins.cors.enabled) {
                        plugins['cors'] = this.plugins.cors.config;
                    }
                    
                    if (Object.keys(plugins).length > 0) {
                        formData.plugins = plugins;
                    }
                    
                    this.loading = true;
                    
                    // 模拟API调用
                    setTimeout(() => {
                        this.$message({
                            message: this.isEdit ? '更新成功！' : '创建成功！',
                            type: 'success'
                        });
                        this.goBack();
                    }, 500);
                }
            });
        },
        goBack() {
            this.$router.push('/routes/list');
        }
    }
}; 